package hn.cch.grammar.io;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.UUID;


/**
 * java.nio.*
 * java >= 1.7
 * - Files
 * - Paths
 * - Path
 */
public class FilesDemo {

    public static String IO = "src/main/resources/io";

    @Test
    public void test0() throws IOException {
        Path dir = Paths.get(IO);
        if (!Files.exists(dir)) {
            Path directories = Files.createDirectories(dir);
        }

        Path path = Paths.get(IO, "file.txt");
        if (!Files.exists(path)){
            Path file = Files.createFile(path);

        }
        // 临时文件
        Path temp = Files.createTempFile(dir, "prefix-", ".suffix");
        Assertions.assertTrue(Files.exists(temp));

        /*
         Path <=> File
         File file = path.toFile();
         Path path = file.toPath();
        */
    }


    @Test
    public void test1() throws IOException {
        Path path = Paths.get(IO, "file.txt");

        // 文件读写
        List<String> lines = Files.readAllLines(path);
        lines.forEach(System.out::println);

        byte[] bytes = UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8);
        Path write = Files.write(Paths.get(IO, "write.txt"), bytes, StandardOpenOption.CREATE);





    }

    @Test
    public void test2() throws Exception {
        Path path = Paths.get(IO, "file.txt");

        // 复制移动
        Path copy = Files.copy(path, Paths.get(IO, "copy.txt"), StandardCopyOption.REPLACE_EXISTING);
        Path move = Files.move(copy, Paths.get(IO, "move.txt"), StandardCopyOption.REPLACE_EXISTING);

        boolean flag = Files.deleteIfExists(move);
        Assertions.assertTrue(flag);

    }

    @Test
    public void test3() throws Exception {
        Path path = Paths.get(IO, "file.txt");
        try (InputStream inputStream = Files.newInputStream(path)) {

        }
    }


}
